/*
 * Copyright (c) 2020, yifengling0. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. No personal names or organizations' names associated with the
 *    Atomthreads project may be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE ATOMTHREADS PROJECT AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "iosdrv.h"
#include "../spi.h"

static int spi_read(FD fd, char* buffer, size_t maxbytes)
{
    return SpiTransfer(fd, NULL, buffer, maxbytes);
}

static int spi_write(FD fd, const char* buffer, size_t nbytes)
{
    return SpiTransfer(fd, buffer, NULL, nbytes);
}

static int spi_ioctl(FD fd, int function, void* arg)
{
    return 0;
}

int SpiTransfer(FD fd, const void* send_buf, void* recv_buf, size_t length)
{
    struct SpiBase* spi = (SpiBase*)fd;

    if (spi->Protected.SpiTransfer != NULL) {
        return spi->Protected.SpiTransfer(spi, send_buf, recv_buf, length);
    }
    else {
        return NG;
    }
}

void SpiCreate(SpiBase* spi, const char *name, int mode, int cpol, int cpha, int dataLines, int bitWidth , uint32_t freq, FSpiTransfer xfer)
{
    spi->super.popen = NULL;
	spi->super.pioctl = spi_ioctl;
	spi->super.pread = spi_read;
	spi->super.pwrite = spi_write;
	spi->super.pclose = NULL;

    spi->Protected.mode = mode;
    spi->Protected.dataLines = dataLines;
    spi->Protected.bitWidth = bitWidth;
    spi->Protected.cpol = cpol;
    spi->Protected.cpha = cpha;
    spi->Protected.freq = freq;
    spi->Protected.SpiTransfer = xfer;

    IosDrvInstall(&spi->super, name);
}
